package com.xjh.him.activity.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;

import com.alibaba.fastjson.JSON;
import com.xjh.him.R;
import com.xjh.him.adapter.ChatGroupCreateAdapter;
import com.xjh.him.core.BaseActivity;
import com.xjh.him.databinding.ActivityUserChooseBinding;
import com.xjh.him.dto.friend.FriendDTO;
import com.xjh.him.dto.usergroup.UserGroupAddDTO;
import com.xjh.him.dto.usergroupmember.UserGroupMemberInviteDTO;
import com.xjh.him.utils.Utils;
import com.xjh.him.utils.XToastUtils;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.widget.actionbar.TitleUtils;

import org.xjh.tool.Checks;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class UserChooseActivity extends BaseActivity<ActivityUserChooseBinding> {
    public static final int PAGE_CODE = 134943;
    public static final String ACTIVITY_TARGET_CREATE_GROUP = "createGroup";
    public static final String ACTIVITY_TARGET_INVITE_USER = "inviteUser";

    public static final String KEY_GROUP_ID = "groupId";
    public static final String KEY_ACTIVITY_TARGET = "activityTarget";

    public Long groupId;
    public String activityTarget;
    public ChatGroupCreateAdapter mAdapter;


    @Override
    protected ActivityUserChooseBinding viewBindingInflate(LayoutInflater inflater) {
        return ActivityUserChooseBinding.inflate(inflater);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        groupId = intent.getLongExtra(KEY_GROUP_ID, -1);
        activityTarget = intent.getStringExtra(KEY_ACTIVITY_TARGET);

        initTitle();
        initViews();
        initListeners();
    }

    public void initTitle() {
        String title = "";
        if (ACTIVITY_TARGET_CREATE_GROUP.equals(activityTarget)) {
            title = "发起群聊";
        }else if (ACTIVITY_TARGET_INVITE_USER.equals(activityTarget)) {
            title = "邀请新成员";
        }
        TitleUtils.addTitleBarDynamic(binding.getRoot(), title, v -> popPage());
    }

    public void initViews() {
        initFriendList();
        if (ACTIVITY_TARGET_CREATE_GROUP.equals(activityTarget)) {
            binding.btnCreate.setText("立即创建");
        }else if (ACTIVITY_TARGET_INVITE_USER.equals(activityTarget)) {
            binding.btnCreate.setText("立即邀请");
        }
    }

    private void initFriendList() {
        String listFriendUrl = Utils.getWebServerApiUrl(this, getString(R.string.api_friend_list));
        SimpleCallBack<Map<String, List<FriendDTO>>> listCB = new SimpleCallBack<Map<String, List<FriendDTO>>>() {
            @Override
            public void onSuccess(Map<String, List<FriendDTO>> groupList) throws Throwable {
                if (!Checks.isEmpty(groupList)) {
                    mAdapter = new ChatGroupCreateAdapter(UserChooseActivity.this, groupList);
                    binding.elvFriendList.setAdapter(mAdapter);
                    binding.elvFriendList.setGroupIndicator(null);

                    mAdapter.setGroupClickListener(groupClickListener);

                    for (int i = 0; i < groupList.size(); i++) {
                        binding.elvFriendList.expandGroup(i);
                    }
                }
            }

            @Override
            public void onError(ApiException e) {
                XToastUtils.toast(e.getDisplayMessage());
            }
        };
        Utils.doGet(listFriendUrl, listCB);
    }

    private void initListeners() {
        binding.btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ACTIVITY_TARGET_CREATE_GROUP.equals(activityTarget)) {
                    createGroup();
                }else if (ACTIVITY_TARGET_INVITE_USER.equals(activityTarget)) {
                    inviteUser();
                }

            }
        });
    }

    @SuppressLint("NewApi")
    private void createGroup() {
        List<FriendDTO> friendDTOList = mAdapter.getSelectList();
        List<Long> selectList = friendDTOList.stream()
                .map(FriendDTO::getId)
                .collect(Collectors.toList());
        String addUrl = Utils.getSevServerApiUrl(UserChooseActivity.this, getString(R.string.api_user_group_add));
        UserGroupAddDTO addDTO = new UserGroupAddDTO();
        addDTO.setUserIdList(selectList);
        SimpleCallBack<Boolean> addCB = new SimpleCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean response) throws Throwable {
                if (response) {
                    XToastUtils.success("创建成功");
                    popPage();
                }
            }

            @Override
            public void onError(ApiException e) {
                XToastUtils.error(e.getDisplayMessage());
            }
        };
        Utils.doPost(addUrl, JSON.toJSONString(addDTO), addCB);
    }

    @SuppressLint("NewApi")
    private void inviteUser() {
        String inviteUrl = Utils.getSevServerApiUrl(this, getString(R.string.api_user_group_member_invite));
        UserGroupMemberInviteDTO inviteDTO = new UserGroupMemberInviteDTO();
        inviteDTO.setUserGroupId(groupId);
        List<FriendDTO> selectList = mAdapter.getSelectList();
        List<UserGroupMemberInviteDTO.InviteUser> inviteUserList = selectList.stream().map(item -> {
            UserGroupMemberInviteDTO.InviteUser user = new UserGroupMemberInviteDTO.InviteUser();
            user.setUserId(item.getId());
            user.setUserNickname(item.getNickname());
            user.setUserAvatar(item.getAvatarUrl());
            return user;
        }).collect(Collectors.toList());
        inviteDTO.setUserList(inviteUserList);
        SimpleCallBack<Boolean> inviteCB = new SimpleCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean response) throws Throwable {
                if (response) {
                    XToastUtils.success("邀请成功");
                    popPage();
                }
            }

            @Override
            public void onError(ApiException e) {
                XToastUtils.error(e.getDisplayMessage());
            }
        };
        Utils.doPost(inviteUrl, JSON.toJSONString(inviteDTO), inviteCB);
    }

    private ExpandableListView.OnGroupClickListener groupClickListener = new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            if (parent.isGroupExpanded(groupPosition)) {
                parent.collapseGroup(groupPosition);
            }else {
                parent.expandGroup(groupPosition);
            }
            return false;
        }
    };
}
